package com.dmx.fw.service.impl;

/**
 * Gu Zhigang
 * 
 */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import com.dmx.fw.bean.mapping.pojo.Resc;
import com.dmx.fw.bean.mapping.pojo.Role;
import com.dmx.fw.dao.interfaces.JdbcDao;
import com.dmx.fw.dao.interfaces.RoleDao;
import com.dmx.fw.resource.SystemProperties;
import com.dmx.fw.service.interfaces.DictionaryService;
import com.dmx.fw.service.interfaces.RoleService;

public class RoleServiceImpl extends BaseServiceImpl implements RoleService {
	private static Logger log = Logger.getLogger(RoleServiceImpl.class);

	private RoleDao roleDao;
	private JdbcDao jdbcDao;

	private DictionaryService dictionaryService;
	
	public Role getRole(Long roleId){
		return this.roleDao.getRole( roleId);
	}
	
	public List findRescByRoleId(Long roleId) {
		return roleDao.findRescByRoleId(roleId);
	}
	
	public List findRescByRole(Long roleId) {
		StringBuffer sql = new StringBuffer();
		if("oracle".equals(SystemProperties.getInstance().getCurrentDataBase())) {
			sql.append("select bb.id,bb.par_func_id,bb.name from ");
			sql.append("(select distinct aa.id,aa.par_func_id,aa.name");
			sql.append(" from SYSTEM_RESC aa connect by prior aa.par_func_id=aa.id");
			sql.append(" start with aa.id in (select b.resc_id ");
			sql.append("from SYSTEM_RESC_ROLE b ");
			sql.append("where b.role_id=");
			sql.append(roleId.longValue());
			sql.append(" )) bb connect by prior bb.id=bb.par_func_id");
			sql.append(" start with (bb.par_func_id is null or bb.par_func_id=0)");
			log.debug("findRescByRole====================================="+sql.toString());
			List list = jdbcDao.queryData(sql.toString());
			return list;
		} else {
			//查找操作员对应资源（叶子结点）SQL
			sql.append("select resc.id,resc.par_func_id,resc.name from SYSTEM_RESC resc ");
			sql.append("inner join SYSTEM_RESC_ROLE rr on resc.id=rr.RESC_ID ");
			sql.append("where rr.ROLE_ID=");
			sql.append(roleId.longValue());

			return getRescByLeavesNode(sql);
		}
	}
	
	public List findAllResc() {
		try {
			StringBuffer sql = new StringBuffer();
			sql.append("select id,par_func_id,name from SYSTEM_RESC bb order by par_func_id,MENU_SORT");
			List list = jdbcDao.queryData(sql.toString());
			return list;
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public List findAllRescByOperator(Long operatorId) {
		StringBuffer sql = new StringBuffer();
		if("oracle".equals(SystemProperties.getInstance().getCurrentDataBase())) {
			sql.append("select bb.id,bb.par_func_id,bb.name from ");
			sql.append("(select distinct aa.id,aa.par_func_id,aa.name");
			sql.append(" from SYSTEM_RESC aa connect by prior aa.par_func_id=aa.id");
			sql.append(" start with aa.id in (select b.resc_id ");
			sql.append("from SYSTEM_RESC_ROLE b, SYSTEM_OPTR_ROLE c ");
			sql.append("where b.role_id = c.role_id and c.optr_id = ");
			sql.append(operatorId);
			sql.append(" )) bb connect by prior bb.id=bb.par_func_id");
			sql.append(" start with (bb.par_func_id is null or bb.par_func_id=0)");

			log.debug("findAllRescByOperator====================================="+sql.toString());
			return jdbcDao.queryData(sql.toString());
		} else {
			//查找操作员对应资源（叶子结点）SQL
			sql.append("select resc.id,resc.par_func_id,resc.name from SYSTEM_RESC resc ");
			sql.append("inner join SYSTEM_RESC_ROLE rr on resc.id=rr.RESC_ID ");
			sql.append("inner join SYSTEM_OPTR_ROLE oor on rr.ROLE_ID=oor.ROLE_ID ");
			sql.append("where oor.OPTR_ID=");
			sql.append(operatorId);
			return getRescByLeavesNode(sql);
		}
	}
	/**
	 * @Description: 通过叶子结点查找上级以及上级的上级 
	 * @param sql 
	 * @return List  
	 * @exception
	 */
	private List getRescByLeavesNode(StringBuffer sql) {
		List leafNodeArray = jdbcDao.queryData(sql.toString());

		Map parentNodeRescMap = new HashMap();
		List parentNodeRescList = new ArrayList();

		for(int i=0;i<leafNodeArray.size();i++) {
			String parentId = ((String)((List)leafNodeArray.get(i)).get(1));
			parentNodeRescMap.put(((String)((List)leafNodeArray.get(i)).get(0)), leafNodeArray.get(i));
			if(parentId!=null&&parentId.length()>0&&!"0".equals(parentId)) {
				recursiveParentsResc(parentId,parentNodeRescMap,parentNodeRescList);
			}
		}

		for(int i=0;i<parentNodeRescList.size();i++) {
			leafNodeArray.add(parentNodeRescList.get(i));
		}
		log.debug("findAllRescByOperator====================================="+sql.toString());
		return leafNodeArray;
	}
	/**
	 * @Fields searchParentSql : 通用的通过id查询一个资源的SQL
	 */
	private final static String searchParentSql = "select distinct resc.id,resc.par_func_id,resc.name from SYSTEM_RESC resc where resc.id=";
	/**
	 * @Description: 通过给定ID递归上级结点
	 * @param id
	 * @param @param parentNodeRescMap
	 * @param @param parentNodeRescList  
	 * @return void  
	 * @exception
	 */
	private void recursiveParentsResc(String id,Map<String, List<String>> parentNodeRescMap,List<List<String>> parentNodeRescList) {
		String parentId = null;
		if(parentNodeRescMap.get(id)==null) {
			List<List<String>> list = jdbcDao.queryData(searchParentSql+id);
			if(list.size()==1) {
				List<String> node = (List<String>)list.get(0);
				parentId = (String)node.get(1);
				parentNodeRescMap.put((String)node.get(0), node);
				parentNodeRescList.add(node);
			}
		}
		if(parentId!=null&&parentId.length()>0&&!"0".equals(parentId)) {
			recursiveParentsResc(parentId,parentNodeRescMap,parentNodeRescList);
		}
	}

	public void save(Role role, String[] funcArray) {
		Set<Resc> functions = new HashSet<Resc>();
		if (funcArray != null && funcArray.length > 0) {
			for (int i = 0; i < funcArray.length; i++) {
				Resc function = (Resc) roleDao.getObject(Resc.class, Long.parseLong(funcArray[i]));
				functions.add(function);
			}
			role.setRescs(functions);
		}
		roleDao.save(role);
	}

	public void update(Role role, String[] funcArray) {
		Role db = (Role) roleDao.getObject(Role.class, role.getId());
		// 先清空，再保存功能权限
		db.setRescs(null);
		Set<Resc> functions = new HashSet<Resc>();
		if (funcArray != null && funcArray.length > 0) {
			for (int i = 0; i < funcArray.length; i++) {
				Resc function = (Resc) roleDao.getObject(Resc.class, Long.parseLong(funcArray[i]));
				functions.add(function);
			}
			db.setRescs(functions);
		}
		db.setName(role.getName());
		db.setRemark(role.getRemark());
		roleDao.save(db);
	}

	public boolean checkRoleNameUnique(Role role) {
		boolean flag = true;
		List temp = roleDao.findRole(role);
		if (temp == null || temp.isEmpty()) {
			flag = false;
		}
		return flag;
	}

	public List findOperatorByRoleId(Long roleId) {
		return roleDao.findOperatorByRoleId(roleId);
	}

	public void delete(Role role) {
		roleDao.removeObject(Role.class, role.getId());
	}

	public RoleDao getRoleDao() {
		return roleDao;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public JdbcDao getJdbcDao() {
		return jdbcDao;
	}

	public void setJdbcDao(JdbcDao jdbcDao) {
		this.jdbcDao = jdbcDao;
	}

	public DictionaryService getDictionaryService() {
		return dictionaryService;
	}

	public void setDictionaryService(DictionaryService dictionaryService) {
		this.dictionaryService = dictionaryService;
	}

}
